package com.am.controller;

import com.alibaba.fastjson.JSON;
import com.am.entity.OperateReq;
import com.am.entity.OperateResp;
import com.am.service.WebsocketHandler;
import com.am.util.ServerEncoder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

//encoders添加编码器 ， 为了能够传递对象
@ServerEndpoint(value = "/websocket", encoders = {ServerEncoder.class})
@Component
@Slf4j
public class WebsocketController {

    private static final WebsocketHandler websocketHandler;

    static {
        websocketHandler = new WebsocketHandler();
    }

    /**
     * 连接成功
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("open: " + String.valueOf(session));
    }

    /**
     * 客户端向服务端发送消息
     *
     * @param session
     * @param message
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        OperateReq req = JSON.parseObject(message, OperateReq.class);

        websocketHandler.FractionalTreatment(session, req);
    }
  /*  @OnMessage
    public void onMessage(Session session,Object message) {
        log.info("前端向后端发消息");
        websocketHandler.FractionalTreatment(session,message);
    }*/


    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        log.info("onclose:" + session);
    }

    /**
     * 发送错误时接收的方法
     *
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.info("err: " + String.valueOf(error));
    }
}
